/*
 * @Author: huangyingli
 * @Date: 2023-02-08 15:56:02
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-22 18:58:15
 * @Description:
 */
import { useEffect } from 'react';

import { useSelector, useDispatch } from 'react-redux';
import { getIsLogin, fetchIsLogin, getLoading } from '../redux/common';
import { useNavigate, useMatch } from 'react-router-dom';
import { ROUTE_PATH } from '../config/routePath';

export function useBeforeRouteEach() {
  const dispatch = useDispatch();
  const isLogin = useSelector(getIsLogin);
  const loading = useSelector(getLoading);
  // const location = useLocation();
  const navigate = useNavigate();
  // const pathname = location.pathname
  const isLoginRoute = useMatch(ROUTE_PATH.LOGIN);
  useEffect(() => {
    console.log('请求是否登录接口');
    console.log('是否是登录', isLoginRoute);
    dispatch(fetchIsLogin());
  }, []);
  useEffect(() => {
    if (isLogin === true) {
      if (isLoginRoute) {
        navigate(ROUTE_PATH.ROOT);
      } else {
        // navigate(pathname)
      }
    } else if (isLogin === false) {
      navigate(ROUTE_PATH.LOGIN);
    }
  }, [isLogin, loading]);

  return isLogin;
}
